<template>
  <el-dialog :visible.sync="visible" v-dialogDrag :title="title" class="tl-dialog" width="1200px" @open="open" @close="close" top="10px" :append-to-body="true" :modal-append-to-body="true">
    <div style="padding-bottom:10px">
      <!-- 查询界面 -->
      <tl-list-search ref="search" :query-param="queryParam" @search="doQuery" :isDisplayDefaultSearch="false">
        <template slot="search">
          <el-form-item label="审批人">
            <el-input v-model="queryParam.qry_user" placeholder="工号或姓名"></el-input>
          </el-form-item>
          <el-form-item label="决策部门">
            <el-input v-model="queryParam.qry_dept" placeholder="部门名称"></el-input>
          </el-form-item>
        </template>
      </tl-list-search>
      <!-- 列表界面 -->
      <div>
        <!-- 列表选择 -->
        <div class="table-alert-div" ref="selector">
          <el-alert type="success" :closable="false" class="tl-table-alert-info" effect="light">
            <template slot="title">
              已选择&nbsp;<a class="tl-table-alert-info-a1">{{ selectedRows.length }}</a>项&nbsp;&nbsp;
              <a class="tl-table-alert-info-a2" @click="doClearSelected">全部清空</a>
            </template>
          </el-alert>
        </div>
        <!--表格渲染-->
        <el-table class="tl-table" ref="mainTable" :height="tableHeight" v-loading="loading" :data="datas" @selection-change="doSelectChange" @sort-change="doSortChange" @row-dblclick="doRowDbClick" row-key="id" border fit :row-class-name="doChangeRowClassName">
          <el-table-column type="selection" :reserve-selection="true" width="55px" fixed="left" v-if="isSingleSelect === false "> </el-table-column>
          <!-- <el-table-column prop="deptcode" label="部门编码" width="150px" sortable="custom" sort-by="deptcode" align="center" header-align="center"></el-table-column> -->
          <el-table-column prop="dispprojectlevel" label="项目等级" width="100px" sortable="custom" sort-by="projectlevel" align="center" header-align="center"></el-table-column>
          <!-- <el-table-column prop="dispprojecttype" label="可审批的项目类型" width="100px" sortable="custom" sort-by="projecttype" align="center" header-align="center"></el-table-column> -->
          <el-table-column prop="usercode" label="工号" width="150px" sortable="custom" sort-by="usercode" align="center" header-align="center"></el-table-column>
          <el-table-column prop="username" label="姓名" width="150px" sortable="custom" sort-by="username" align="center" header-align="center"></el-table-column>
          <el-table-column prop="deptname" label="决策部门" width="150px" sortable="custom" sort-by="deptname" align="center" header-align="center"></el-table-column>
          <el-table-column prop="description" label="备注" min-width="250px" align="left" header-align="center"></el-table-column>
          <!-- <el-table-column prop="enabled" label="有效" width="100px" sortable="custom" sort-by="enabled" align="center" header-align="center">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.enabled === 1" type="success">是</el-tag>
              <el-tag v-else type="danger">否</el-tag>
            </template>
          </el-table-column> -->
          <el-table-column label="操作" width="80px" align="center" fixed="right" v-if="isSingleSelect === true">
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-finished" @click="doSelectData(scope.row[fieldDefaultKey])">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 列表分页 -->
        <el-row class="pagebar" ref="pager">
          <el-pagination @size-change="doChangeSize" @current-change="doChangeIndex" :current-page="pageInfo.currentPage" :page-sizes="pageInfo.pageSizes" :total="pageInfo.totalCount" layout="total, sizes, prev, pager, next, jumper" background class="tl-table-pagination"> </el-pagination>
        </el-row>
      </div>
    </div>
    <div slot="footer" class="dialog-footer" v-if="isSingleSelect === false">
      <el-button type="text" @click="doCancelEdit">取消</el-button>
      <el-button type="primary" @click="doConfirm">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
/** mixins */
import { mixin_ref_list } from '@tapui/mixins/mixin_ref_list'
/** 子组件 */
/** 工具类 */
import { queryDataCode } from '@tapui/api/dataCode'
import { getAction, putAction, postAction } from '@tapui/utils/http'
import { validateNull } from '@tapui/utils/validate'
import { filterObjectNull } from '@tapui/utils/util'
/** VUE配置 */
export default {
  name: 'TlSdProjectResourcePoolRef',
  components: {},
  mixins: [mixin_ref_list],
  data() {
    return {
      projectlevelList: [],
      projecttypeList: [],
      codeModel: {},
      description: 'SD部门审批人资源池参照页面',
      // 默认Key字段名
      fieldDefaultKey: 'id',
      // 默认显示字段名
      fieldDefaultValue: 'name',
      initSelectedRowKeysArray: [],
      // url配置
      url: {
        list: '/sd/projectResourcePool/refList',
        queryCodeList: '/sd/projectResourcePool/dataCodeList'
      },
      // 排序参数
      sorterInfo: {
        sidx: 'sortcode',
        sord: 'asc'
      }
    }
  },
  props: {
    // 默认显示值
    initDisplayData: {
      default: '',
      type: String
    }
  },
  methods: {
    close() {
      // 清空选择、初始化列表，防止再次进入时加载脏数据
      this.initSelectedRowKeysArray = []
      this.doClearSelected()
    },
    /** 禁用表格双击事件 */
    doRowDbClick(row, column, event) {
      return
    },
    /** 查询数据 */
    loadData(paramMap) {
      if (!this.url.list) {
        this.$tap.alert('请设置查询数据地址!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (validateNull(paramMap) === false && Object.keys(paramMap).indexOf('currentPage') > -1) {
        this.pageInfo.currentPage = paramMap['currentPage']
      }
      // 查询条件
      var params = this.getQueryParams()
      this.loading = true
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            this.datas = res.result.dataList
            this.pageInfo.totalCount = res.result.totalCount
            this.$nextTick(() => {
              if (this.isSingleSelect === false) {
                if (validateNull(this.externalSelectedRowKeys) === false) {
                  // 表示还未进行初始化的数据
                  let externalSelectedRowKeyArray = this.externalSelectedRowKeys.split(',')
                  this.initSelectedRowKeysArray.forEach((selectedKey) => {
                    // 查找已经初始化过的数据，并删除
                    let index = externalSelectedRowKeyArray.findIndex((initKey) => selectedKey === initKey)
                    if (index > -1) {
                      externalSelectedRowKeyArray.splice(index, 1)
                    }
                  })
                  // 当前选中的列表
                  let currentSelectedRowKeys = this.selectedRowKeys
                  this.datas.forEach((item) => {
                    // 表示是否需要初始化该数据
                    let isInitRow = externalSelectedRowKeyArray.includes(item[this.fieldKeyComputed].toString())
                    // 表示该数据是否已被选中
                    let isSelectedRow = currentSelectedRowKeys.includes(item[this.fieldKeyComputed].toString())
                    // 选择：1设定的key不为空、2需要初始化、3未勾选的数据，对其进行勾选操作
                    if (typeof item[this.fieldKeyComputed] !== 'undefined' && isInitRow && !isSelectedRow) {
                      this.$refs.mainTable.toggleRowSelection(item)
                      // 添加到已操作的默认值列表中，用于处理未访问的分页中，未进行勾选的默认值
                      this.initSelectedRowKeysArray.push(item[this.fieldKeyComputed])
                    }
                  })
                }
              }
            })
          } else {
            this.$tap.alert(res.message)
          }
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
        })
    },
    /** 一键选择全部数据 */
    doSelectedAll() {
      if (!this.url.list) {
        this.$tap.alert('请设置查询数据地址!')
        return
      }
      // 查询条件
      let params = this.getQueryParams()
      // 页面大小设为0，以此请求全部数据
      params.pageSize = 0
      this.loading = true
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            let allDatas = res.result.dataList
            // 当前选中的列表
            let currentSelectedRowKeys = this.selectedRowKeys
            // 刷新页面选择
            allDatas.forEach((item) => {
              // 表示该数据是否已被选中
              let isSelectedRow = currentSelectedRowKeys.includes(item[this.fieldKeyComputed].toString())
              if (typeof item[this.fieldKeyComputed] !== 'undefined' && !isSelectedRow) {
                this.$refs.mainTable.toggleRowSelection(item)
                // 将所有默认值添加到已操作的默认值列表中
                this.initSelectedRowKeysArray = this.externalSelectedRowKeys.split(',')
              }
            })
            // 重新加载该页数据，刷新选项
            this.loadData({})
          } else {
            this.$tap.alert(res.message)
          }
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
        })
    },
    /** 多选数据 */
    doConfirm() {
      let selectedValues = ''
      let selectedKeys = ''

      // 外部传入的name和key列表
      if (!validateNull(this.externalSelectedRowKeys) && !validateNull(this.initDisplayData)) {
        let keyArray = this.externalSelectedRowKeys.split(',').filter(item => item)
        let nameArray = this.initDisplayData.split(',').filter(item => item)
        // 查找未进行初始化的外部数据，重新添加
        keyArray.forEach((key, index) => {
          if (!this.initSelectedRowKeysArray.includes(key)) {
            selectedValues += nameArray[index] + ','
            selectedKeys += key + ','
            // selectedRows添加数据
            if (!this.selectedRows.find(item => item[this.fieldKeyComputed] === key)) {
              let extraData = {}
              extraData[this.fieldKeyComputed] = key
              extraData[this.fieldValueComputed] = nameArray[index]
              this.selectedRows.push(extraData)
            }
          }
        })
      }
      // 其余部分未改动
      this.selectedRows.forEach((item) => {
        selectedValues += item[this.fieldValueComputed] + ','
      })
      this.selectedRows.forEach((item) => {
        selectedKeys += item[this.fieldKeyComputed] + ','
      })
      if (selectedValues.length > 0) {
        selectedValues = selectedValues.substring(0, selectedValues.length - 1)
      }
      if (selectedKeys.length > 0) {
        selectedKeys = selectedKeys.substring(0, selectedKeys.length - 1)
      }
      this.$emit('confirm', this.selectedRows, selectedKeys, selectedValues)
      this.visible = false
    }
  },
  created() {
    getAction(this.url.queryCodeList, {}).then((res) => {
      if (res.success) {
        this.codeModel = res.result
      } else {
        this.$tap.alert(res.message, 'warning')
      }
    })
  }
}
</script>

